'use client';

import type { TMetadata } from '@/types';
import LoadPage from '@/app/[locale]/load/load';
import ErrorPage from '@/app/[locale]/error/error';
import { clientQueryUserDetails } from '@/services/api';
import { useInfiniteQuery } from '@tanstack/react-query';
import FooterH5IcpPage from '@/app/[locale]/mobile/footerH5Icp';
import FooterH5Page from '@/app/[locale]/mobile/footerH5';
import { UserIdH5PageContext } from '@/contexts/mobile/userId';
import BtnBoxUserIdH5Page from '@/app/[locale]/mobile/users/home/btnBox';
import BtnUserIdH5Page from '@/app/[locale]/mobile/users/home/btn';
import PostUserIdH5Page from '@/app/[locale]/mobile/users/home/post';
import StatisticsUserIdH5Page from '@/app/[locale]/mobile/users/home/statistics';
import AboutMeUserIdH5Page from '@/app/[locale]/mobile/users/home/aboutMe';
import ContactUserIdH5Page from '@/app/[locale]/mobile/users/home/contact';
import useToast from 'hooks/useToast';
import NameUserIdH5Page from '@/app/[locale]/mobile/users/home/name';
import type { IQueryParams, IUserClientDetails } from '@/interfaces';

export default function UserIdH5Page({ metadata }: { metadata: TMetadata }) {
  return (
    <>
      <UserId metadata={metadata} />
      <FooterH5IcpPage metadata={metadata} />
      <FooterH5Page metadata={metadata} />
    </>
  );
}

const UserId = ({ metadata }: { metadata: TMetadata }) => {
  const { show } = useToast();

  const clientQueryUserDetailsQuery = useInfiniteQuery(
    metadata.all['userId'].k,
    async (context) => {
      return (await clientQueryUserDetails({
        id: context.queryKey[2] + '',
        query: {
          ...(context.queryKey[4] as IQueryParams),
          ...context.pageParam,
        },
      })) as IUserClientDetails;
    },
    {
      enabled: !!metadata.all['userId'],
      keepPreviousData: true,
      getPreviousPageParam: (firstPage) => {
        if (firstPage.data && firstPage.data.pageable.previous) {
          return {
            page: Math.max(firstPage.data.pageable.page - 1, 0),
          };
        }
      },
      getNextPageParam: (lastPage) => {
        if (lastPage.data && lastPage.data.pageable.next) {
          return {
            page: Math.min(
              lastPage.data.pageable.page + 1,
              lastPage.data.pageable.pages,
            ),
          };
        }
      },
      initialData: () => {
        if (metadata.all['userId']) {
          return {
            pages: [metadata.all['userId'].v as IUserClientDetails],
            pageParams: [
              {
                page: Math.max(
                  ((metadata.all['userId'].k[4] as IQueryParams).page ?? 1) - 1,
                  0,
                ),
              },
            ],
          };
        }
      },
    },
  );

  function emptyPrompt(prompt: string = '没有内容') {
    show({
      message: prompt,
    });
  }

  if (clientQueryUserDetailsQuery.data) {
    const user = clientQueryUserDetailsQuery.data.pages[0].user;

    return (
      <UserIdH5PageContext.Provider value={{ metadata }}>
        <div className="col p-2">
          <div className="card rounded-5 border-0">
            <div className="card-body">
              <div className="vstack gap-3">
                <NameUserIdH5Page user={user} />

                <div></div>

                <BtnBoxUserIdH5Page>
                  <BtnUserIdH5Page
                    path="/login"
                    iName="person"
                    name="快捷登录"
                  />
                  <BtnUserIdH5Page
                    path="/register"
                    iName="person-add"
                    name="快速注册"
                  />
                </BtnBoxUserIdH5Page>

                <BtnBoxUserIdH5Page>
                  {user ? (
                    <BtnUserIdH5Page
                      metadata={metadata}
                      content={<PostUserIdH5Page id={user.id} />}
                      name="相关文章"
                    />
                  ) : (
                    <BtnUserIdH5Page
                      fn={emptyPrompt.bind(this, '暂时没有相关文章')}
                      name="相关文章"
                    />
                  )}

                  {user ? (
                    <BtnUserIdH5Page
                      metadata={metadata}
                      content={<PostUserIdH5Page id={user.id} type="section" />}
                      name="相关内容"
                    />
                  ) : (
                    <BtnUserIdH5Page
                      fn={emptyPrompt.bind(this, '暂时没有相关内容')}
                      name="相关内容"
                    />
                  )}

                  {user ? (
                    <BtnUserIdH5Page
                      metadata={metadata}
                      content={<PostUserIdH5Page id={user.id} type="tag" />}
                      name="相关标签"
                    />
                  ) : (
                    <BtnUserIdH5Page
                      fn={emptyPrompt.bind(this, '暂时没有相关标签')}
                      name="相关标签"
                    />
                  )}

                  {user ? (
                    <BtnUserIdH5Page
                      metadata={metadata}
                      name="相关统计"
                      content={<StatisticsUserIdH5Page user={user} />}
                    />
                  ) : (
                    <BtnUserIdH5Page
                      fn={emptyPrompt.bind(this, '暂时没有相关统计')}
                      name="相关统计"
                    />
                  )}
                </BtnBoxUserIdH5Page>

                <BtnBoxUserIdH5Page>
                  <BtnUserIdH5Page
                    metadata={metadata}
                    name="关于我"
                    content={
                      <AboutMeUserIdH5Page
                        about={user ? user.details.about : undefined}
                      />
                    }
                  />
                  <BtnUserIdH5Page
                    metadata={metadata}
                    iName="person-lines-fill"
                    name="联系方式"
                    content={
                      <ContactUserIdH5Page
                        contacts={user ? user.details.contacts : undefined}
                      />
                    }
                  />
                  <BtnUserIdH5Page path="/terms" name="服务条款" />
                  <BtnUserIdH5Page path="/privacy-policy" name="隐私政策" />
                </BtnBoxUserIdH5Page>

                <div></div>
              </div>
            </div>
          </div>
        </div>
      </UserIdH5PageContext.Provider>
    );
  }

  if (clientQueryUserDetailsQuery.error) {
    return <ErrorPage error={clientQueryUserDetailsQuery.error} />;
  }

  return <LoadPage />;
};
